package org.foreverframework.account.email;

import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class AccountEmailServiceImpl implements AccountEmailService {

	private JavaMailSender javaMailSender;
	private String fromEmail;

	public void sendMail(String to, String subject, String htmlText)
			throws AccountEmailException {
		try {
			MimeMessage msg = javaMailSender.createMimeMessage();
			MimeMessageHelper msgHelper = new MimeMessageHelper(msg);
			msgHelper.setFrom(fromEmail);
			msgHelper.setTo(to);
			msgHelper.setSubject(subject);
			msgHelper.setText(htmlText, true);
			javaMailSender.send(msg);
		} catch (Exception e) {
			throw new AccountEmailException("Faild to send mail.", e);
		}
	}
	
	public JavaMailSender getJavaMailSender() {
		return javaMailSender;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

	
	//test method 
	public String getFromEmail() {
		return fromEmail;
	}

	public void setFromEmail(String fromEmail) {
		this.fromEmail = fromEmail;
	}

	public void setProtocol(String protocol) {
		((JavaMailSenderImpl)javaMailSender).setProtocol(protocol);
	}

	public void setHost(String host) {
		((JavaMailSenderImpl)javaMailSender).setHost(host);		
	}

	public void setPort(int port) {
		((JavaMailSenderImpl)javaMailSender).setPort(port);		
	}

	public void setUsername(String username) {
		((JavaMailSenderImpl)javaMailSender).setUsername(username);
	}

	public void setPassword(String password) {
		((JavaMailSenderImpl)javaMailSender).setPassword(password);		
	}

	public void setEncoding(String encoding){
		((JavaMailSenderImpl)javaMailSender).setDefaultEncoding(encoding);
	}
	
	public void isAuth(boolean auth) {
		String protocol = ((JavaMailSenderImpl)javaMailSender).getProtocol();
		((JavaMailSenderImpl)javaMailSender).getJavaMailProperties().put("mail."+protocol+".auth", auth);		
	}

	public String getFormEmail() {
		return fromEmail;
	}

}
